let tbody = document.querySelector("tbody");
// 省市县
let provinceEle = document.querySelector('[name="province"]');
let cityEle = document.querySelector('[name="city"]');
let countyEle = document.querySelector('[name="county"]');
let nameEle = document.querySelector('[name="name"]');
let ageEle = document.querySelector('[name="age"]');
let groupEle = document.querySelector('[name="group"]');
let sexEles = document.querySelectorAll('[name="sex"]');
let phoneEle = document.querySelector('[name="phone"]');
let salaryEle = document.querySelector('[name="salary"]');
let truesalaryEle = document.querySelector('[name="truesalary"]');
// 模态框
let content = document.querySelector(".content");
// 模态框标题
let addModalLabel = document.querySelector("#addModalLabel");
// 模态框确认按钮
let btnsubmit = document.querySelector(".btnsubmit");
//  模态框确认重置按钮
let btnreset = document.querySelector(".btnreset");
// 添加学员按钮
let btnbutton = document.querySelector(".btnbutton");

// 数据渲染
function render() {
  axios({
    url: "/student/list",
    method: "get",
  }).then((res) => {
    // console.log(res);
    let htmlStr = "";
    res.data.data.forEach(function (value, index) {
      htmlStr += `
            <tr>
        <th scope="row">${value.id}</th>
        <td>${value.name}</td>
        <td>${value.age}</td>
        <td>${value.sex}</td>
        <td>${value.group}</td>
        <td>${value.phone}</td>
        <td>${value.salary}</td>
        <td>${value.truesalary}</td>
        <td>${value.province + value.city + value.county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm btnedit" data-id="${value.id}">修改</button>
          <button type="button" class="btn btn-danger btn-sm btndel" data-id="${value.id}">删除</button>
        </td>
      </tr>
            `;
    });
    tbody.innerHTML = htmlStr;
  });
}
render();

// 省
axios({
  url: "/geo/province",
}).then(function (res) {
  //    console.log(res)
  //    默认值
  let str = '<option selected value="">--省--</option>';
  res.data.forEach(function (value, index) {
    str += `
       <option value="${value}">${value}</option>
       `;
  });
  provinceEle.innerHTML = str;
});

// 市
provinceEle.addEventListener("change", function () {
  let pname = provinceEle.value;
  // 判断是否选择了省，没有就不用发请求了
  if (!pname) {
    return;
  } else {
    axios({
      url: "/geo/city",
      method: "get",
      params: { pname },
    }).then(function (res) {
      //  console.log(2,res)
      let str = '<option selected value="">--市--</option>';
      res.data.forEach(function (value, index) {
        str += `
                 <option value="${value}">${value}</option>
                 `;
      });
      cityEle.innerHTML = str;
    });
  }
});

// 县
cityEle.addEventListener("change", function () {
  let pname = provinceEle.value;
  let cname = cityEle.value;
  // 判断是否选择了市，没有就不用发请求了
  if (!cname) {
    return;
  } else {
    axios({
      url: "/geo/county",
      method: "get",
      params: { pname, cname },
    }).then(function (res) {
      //  console.log(3,res)
      let str = '<option selected value="">--县--</option>';
      res.data.forEach(function (value, index) {
        str += `
                 <option value="${value}">${value}</option>
                 `;
      });
      countyEle.innerHTML = str;
    });
  }
});

// 表单输入验证
function student() {
  return {
    fields: {
      name: {
        validators: {
          notEmpty: {
            message: "姓名不能为空",
          },
          stringLength: {
            min: 2,
            max: 10,
            message: "姓名长度2~10位",
          },
        },
      },
      age: {
        validators: {
          notEmpty: {
            message: "年龄不能为空",
          },
          greaterThan: {
            value: 18,
            message: "年龄不能小于18岁",
          },
          lessThan: {
            value: 60,
            message: "年龄不能超过60岁",
          },
        },
      },
      sex: {
        validators: {
          choice: {
            min: 1,
            max: 1,
            message: "请选择性别",
          },
        },
      },
      group: {
        validators: {
          notEmpty: {
            message: "组号不能为空",
          },
          regexp: {
            regexp: /^\d{1,2}$/,
            message: "请选择有效的组号",
          },
        },
      },
      phone: {
        validators: {
          notEmpty: {
            message: "手机号不能为空",
          },
          regexp: {
            regexp: /^1\d{10}$/,
            message: "请填写有效的手机号",
          },
        },
      },
      salary: {
        validators: {
          notEmpty: {
            message: "实际薪资不能为空",
          },
          greaterThan: {
            value: 800,
            message: "期望薪资不能低于800",
          },
          lessThan: {
            value: 100000,
            message: "期望薪资不能高于100000",
          },
        },
      },
      truesalary: {
        validators: {
          notEmpty: {
            message: "实际薪资不能为空",
          },
          greaterThan: {
            value: 800,
            message: "实际薪资不能低于800",
          },
          lessThan: {
            value: 100000,
            message: "实际薪资不能高于100000",
          },
        },
      },
      province: {
        validators: {
          notEmpty: {
            message: "省份必填",
          },
        },
      },
      city: {
        validators: {
          notEmpty: {
            message: "市必填",
          },
        },
      },
      county: {
        validators: {
          notEmpty: {
            message: "县必填",
          },
        },
      },
    },
  };
}

// 添加或编辑
$(".add-form")
  .bootstrapValidator(student())
  .on("success.form.bv", function (e) {
    e.preventDefault();

    let formdata = new FormData(this);
    let data = {};
    formdata.forEach(function (value, index) {
      data[index] = value;
    });
    if (addModalLabel.innerHTML == "录入新学员") {
      axios({
        url: "/student/add",
        method: "post",
        data,
      }).then(function (res) {
        console.log(res);
        toastr.success("添加成功");
        $("#addModal").modal("hide");
        render();
      });
    } else {
      // 编辑
      // 添加参数
      data.id = id;
      // ajax请求
      axios({
        url: "/student/update",
        method: "put",
        data,
      }).then(function (res) {
        console.log(res);
        $("#addModal").modal("hide");
        render();
        // 数据回填
        nameEle.value = "";
        ageEle.value = "";
        phoneEle.value = "";
        salaryEle.value = "";
        truesalaryEle.value = "";
        groupEle.value = "";
        // 单选框赋值
        sexEles.value = sexEles[0];
        // 下拉列表赋值
        provinceEle.value = '<option selected value="">--省--</option>';
        cityEle.innerHTML = '<option selected value="">--市--</option>';
        countyEle.innerHTML = '<option selected value="">--县--</option>';
        toastr.success("编辑成功");
        
      });
    }
  });

//   数据删除
tbody.addEventListener("click", function (e) {
  if (e.target.classList.contains("btndel")) {
    let id = e.target.dataset.id;
    //   console.log(id)
    axios({
      url: "/student/delete",
      method: "delete",
      params: { id: id },
    }).then(function (res) {
      //   console.log(res)
      toastr.success("删除成功");
      render();
    });
  }
});

//  弹出模态框，修改标题
btnbutton.addEventListener("click", function () {
  $("#addModal").modal("show");
  addModalLabel.innerHTML = "录入新学员";
  btnsubmit.innerHTML = "确认添加";
});

// 修改,根据个人id查询，然后数据回填
tbody.addEventListener("click", function (e) {
  if (e.target.classList.contains("btnedit")) {
    $("#addModal").modal("show");
    addModalLabel.innerHTML = "编辑学员信息";
    btnsubmit.innerHTML = "确认编辑";

    // 获取自定义属性
    id = e.target.dataset.id;
    axios({
      url: "/student/one",
      method: "get",
      params: { id },
    }).then(function (res) {
      console.log(res);
      let data = res.data.data;
      // 数据回填
      nameEle.value = data.name;
      ageEle.value = data.age;
      phoneEle.value = data.phone;
      salaryEle.value = data.salary;
      truesalaryEle.value = data.truesalary;
      groupEle.value = data.group;
      // 单选框赋值
      document.querySelector(`input[value=${data.sex}]`).checked = true;
      // 下拉列表赋值
      provinceEle.value = data.province;
      cityEle.innerHTML = `<option selected value="${data.city}">${data.city}</option>`;
      countyEle.innerHTML = `<option selected value="${data.county}">${data.county}</option>`;

      // 自动的触发省下拉列表的选项切换事件
      // 创建一个事件对象
      let ev = document.createEvent('HtmlEvents')
      // 初始化事件，指定事件类型
      ev.initEvent('change', true, true)
      // 使用元素触发事件
      provinceEle.dispatchEvent(ev)
      setTimeout(() => {
        cityEle.value = data.city

        let ev = document.createEvent('HtmlEvents')
        // 初始化事件，指定事件类型
        ev.initEvent('change', true, true)
        // 使用元素触发事件
        cityEle.dispatchEvent(ev)
        setTimeout(() => {
          countyEle.value = data.county
        }, 500)
      }, 500)
    })
}
});
